import { createRouter, createWebHistory } from 'vue-router'
import adminRoutes from './admin'
import userRoutes from './user'
import { useUserStore } from '@/store'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    component: () => import('@/views/public/index.vue'),
  },
  {
    path: '/login',
    component: () => import('@/views/public/login.vue'),
  },
  {
    path: '/404',
    component: () => import('@/views/public/404.vue'),
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
  },
]

// 合并路由
routes.push(userRoutes)
routes.push(adminRoutes)

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
})

/**
 * 路由拦截
 * / -> 首页跳转
 * login,404 -> 登录,404页面
 * 访问 / 没登录 -> 重定向到登录页面
 */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  console.log('跳转到', to.path)

  if (to.path === '/404') {
    return next()
  }

  if (!userStore.isLogined) {
    // 自动登录
    if (!userStore.tryLogin) {
      userStore.tryLogin = true
      try {
        await userStore.login()
      } catch (e) {
        if (to.path !== '/login') ElMessage.error(e.message)
        return to.path === '/login' ? next() : next('/login')
      }
      ElMessage.success('自动登录成功')
    } else {
      return to.path === '/login' ? next() : next('/login')
    }
  }

  // 以下是已登录或自动登录成功

  /* 登录后跳首页 */
  if (to.path === '/' || to.path === '/login') {
    return next(userStore.isAdmin ? '/admin/dashboard' : '/user/home')
  }

  /* 需要权限且角色不符 → 拦截 */
  if (to.meta?.role && !to.meta.role.includes(userStore.role)) {
    ElMessage.warning('您暂无权限访问该页面')
    return next('/404')
  }

  /* 其余放行 */
  next()
})

export default router
